import React, { useCallback, useState } from "react";

const request = <T,>(url: string, params: Object): Promise<T> => {
  const body = JSON.stringify(params);
  return fetch(url, {
    headers: {
      "content-type": "application/json",
    },
    body,
    credentials: "include",
  })
    .then((res) => res.json())
    .then((data) => data);
};

const fetchData = (params: Object) =>
  request<Array<{ name: string; age: number }>>("/app", params);

const useFetchHandle = <T,>(
  api: (params: any) => Promise<T>,
  handleSuccess: (params: T) => void,
  handleFail?: (error: string) => void
) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<T>();
  const loadData = async (params: Object) => {
    try {
      setLoading(true);
      const data: T = await api(params);
      handleSuccess(data);
      setLoading(false);
      setData(data);
    } catch (e: any) {
      setLoading(false);
      setData(undefined);
      const message = e?.message ?? "出现错误";
      handleFail?.(message);
    }
  };

  return [data, loadData, loading] as const;
};

const Test = () => {
  // useFetch 综合起来
  const [data, loadData, loading] = useFetchHandle(
    fetchData,
    useCallback((data) => {
      console.log(data);
    }, [])
  );
  return <div></div>;
};

export default Test;
